package com.analyse.stock.service.impl;

import com.analyse.stock.service.IQuartzService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class QuartzService implements IQuartzService {

    @Resource
    private Scheduler scheduler;

    private static final String DEFAULT_JOB_GROUP = "default_job_group";

    private static final String DEFAULT_TRIGGER_GROUP = "default_trigger_group";

    private static final String TRIGGER_PRE = "Trigger_";

    @Override
    public String addCronJob(String jobName, String cron, String jobClassName) {
        try {
            // 当前任务不存在才进行添加
            JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
            if (scheduler.checkExists(jobKey)) {
                log.info("[添加定时任务]已存在该作业，jobkey为：{}", jobKey);
                return "已存在该作业";
            }
            // 构建 Job
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withIdentity(jobKey).build();

            // cron表达式定时构造器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);

            // 构建 Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + jobName, DEFAULT_TRIGGER_GROUP))
//                .startAt(DateUtil.parseDate(start))
//                .endAt(DateUtil.parseDate(end))
                    .withSchedule(cronScheduleBuilder).build();
            // 启动调度器
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "SUCCESS";
        } catch (Exception e) {
            log.error("[新增定时任务]失败，报错：", e);
            return "FAIL";
        }
    }

    @Override
    public String deleteCronJob(String jobName) {
        try {
            String triggerName = TRIGGER_PRE + jobName;
            JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, DEFAULT_TRIGGER_GROUP);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (null == trigger) {
                log.info("[停止定时任务]根据triggerName:{}和triggerGroup:{}未查询到相应的trigger！",triggerName,DEFAULT_TRIGGER_GROUP);
                return "SUCCESS";
            }
            //暂停触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
            log.info("[删除定时任务]jobName:{},jobGroup:{}, triggerName:{}, triggerGroup:{},停止--------------",
                    jobName, DEFAULT_JOB_GROUP, triggerName, DEFAULT_TRIGGER_GROUP);
            return "SUCCESS";

        } catch (SchedulerException e) {
            log.error("[删除定时任务]失败，报错：", e);
            return "FAIL";
        }
    }

    @Override
    public String pauseTrigger(String jobName) {
        try {
            String triggerName = TRIGGER_PRE + jobName;
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, DEFAULT_TRIGGER_GROUP);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (null == trigger) {
                log.info("[暂停定时任务]根据triggerName:{}和triggerGroup:{}未查询到相应的trigger！",triggerName,DEFAULT_TRIGGER_GROUP);
                return "SUCCESS";
            }
            //暂停触发器
            scheduler.pauseTrigger(triggerKey);
            log.info("[暂停定时任务]jobName:{}, triggerName:{}, triggerGroup:{},停止--------------",jobName, triggerName, DEFAULT_TRIGGER_GROUP);
            return "SUCCESS";
        } catch (SchedulerException e) {
            log.error("[停止定时任务]失败，报错：", e);
            return "FAIL";
        }
    }

    @Override
    public String resumeTrigger(String jobName) {
        try {
            String triggerName = TRIGGER_PRE + jobName;
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, DEFAULT_TRIGGER_GROUP);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (null == trigger) {
                log.info("[恢复定时任务]根据triggerName:{}和triggerGroup:{}未查询到相应的trigger！",triggerName,DEFAULT_TRIGGER_GROUP);
                return "SUCCESS";
            }
            //暂停触发器
            scheduler.resumeTrigger(triggerKey);
            log.info("[恢复定时任务]jobName:{},jobName:{}, triggerName:{},恢复--------------",jobName, DEFAULT_TRIGGER_GROUP, triggerName);
            return "SUCCESS";
        } catch (SchedulerException e) {
            log.error("[恢复定时任务]失败，报错：", e);
            return "FAIL";
        }
    }

    public static Job getClass(String className) throws Exception {
        Class<?> classTemp = Class.forName(className);
        return (Job) classTemp.newInstance();
    }

    //立即执行一次任务
    @Override
    public String executeImmediately(String jobName, String jobClassName) {
        try {
            JobKey jobKey = JobKey.jobKey(jobName, DEFAULT_JOB_GROUP);
            JobDetail job = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withIdentity(jobKey).build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(TriggerKey.triggerKey(TRIGGER_PRE + jobName, DEFAULT_TRIGGER_GROUP))
                    .startNow()
                    .build();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
            return "SUCCESS";
        } catch (Exception e) {
            log.error("[立即执行一次任务，不定时]失败，报错：", e);
            return "FAIL";
        }
    }
}
